package com.timk.goserver.server.servlets;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import com.timk.goserver.client.model.ClientUserInfo;
import com.timk.goserver.server.model.ServerUserInfo;
import com.timk.goserver.server.util.HibernateUtil;
import com.timk.goserver.server.util.RatingManager;

/**
 * CreateUserServlet servlet
 * @author TKington
 *
 */
public class CreateUserServlet extends HttpServlet {	// NOPMD - Complexity

	protected void doPost(HttpServletRequest request,	// NOPMD - Complexity
			HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String password2 = request.getParameter("password2");
		String fullname = request.getParameter("fullname");
		String email = request.getParameter("email");
		String rank = request.getParameter("rank");
		String grade = request.getParameter("grade");
		String notification = request.getParameter("notification");
		
		if(username == null || password == null || password2 == null ||
				!password.equals(password2)) {
			response.sendRedirect("newuser.html");
			return;
		}
		
		ServerUserInfo user = ServerUserInfo.findUser(username, null);
		if(user != null) {
			response.sendRedirect("newuser.html");
			return;
		}
		
		int numRank;
		
		try {
			numRank = Integer.parseInt(rank);
		} catch(NumberFormatException e) {
			numRank = 20;
			grade = "kyu";
		}
		
		int rating = RatingManager.stringToRating(numRank, grade);
		if(rating == -1) {
			response.sendRedirect("newuser.html");
			return;
		}
		
		int notifySetting;
		if("none".equals(notification)) {
			notifySetting = ClientUserInfo.NOTIFICATION_NONE;
		} else if("notify".equals(notification)) {
			notifySetting = ClientUserInfo.NOTIFICATION_NOTIFY;
		} else {
			notifySetting = ClientUserInfo.NOTIFICATION_FULL_BOARD;
		}
		
		try {
			user = new ServerUserInfo(username, password, fullname, email, rating,
					notifySetting);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace(response.getWriter());
			return;
		}
		
		Session hbSession = HibernateUtil.startTrans();
		hbSession.save(user);
		hbSession.getTransaction().commit();
		
		LoginServlet.initSession(request, response, username);
		response.sendRedirect("intro.html");
	}
}
